<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getCategoryListApi, saveCategoryInfoApi, deleteCategoryListApi } from '@/api/Sales/category'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { createImageViewer } from '@/components/ImageViewer'
import { ElMessage } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getCategoryListApi(unref(searchParams))
    console.log(res)
    return {
      list: res.data.list || [],
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await deleteCategoryListApi(unref(id))
    return !!res
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, delList } = tableMethods

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('sales.category.name'),
    component: 'Input'
  }
])
const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const AddAction = () => {
  dialogTitle.value = t('button.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveCategoryInfoApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      ElMessage.success(t('common.saveSuccess'))
      dialogVisible.value = false
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

const delLoading = ref(false)
const id = ref<number>()

const delData = async (row) => {
  id.value = row.id
  delLoading.value = true
  await delList(1).finally(() => {
    delLoading.value = false
  })
}

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('table.index'),
    type: 'index'
  },
  {
    field: 'name',
    label: t('sales.category.name')
  },
  {
    field: 'picture',
    label: t('sales.category.picture'),
    slots: {
      default: (data: any) => {
        return (
          <>
            <img src={data.row.picture} onClick={() => {createImageViewer({urlList: [data.row.picture]})}}/>
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('table.action'),
    width: 88,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="danger" onClick={() => delData(row)}>{t('button.del')}</BaseButton>
          </>
        )
      }
    }
  }
])

</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('button.add') }}</BaseButton>
    </div>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write ref="writeRef" :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('button.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('button.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
